#pragma once

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <functional>
#include <cstring>
#include <unistd.h>
#include "err.hpp"

using func_t = std::function<std::string(const std::string str)>;

uint16_t default_port = 8080;

int backlog = 32;

class ns_server
{
public:
    ns_server(func_t func, uint16_t port = default_port)
        : _func(func), _port(port), _listensock(-1)
    {
    }

    void init()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            std::cout << "creat socket fail" << std::endl;
            exit(SOCK_ERR);
        }
        std::cout << "creat socket success" << std::endl;

        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            std::cout << "bind socket fail" << std::endl;
            exit(BIND_ERR);
        }
        std::cout << "bind socket success" << std::endl;

        if (listen(_listensock, backlog) < 0)
        {
            std::cout << "listen fail" << std::endl;
            exit(LISTEN_ERR);
        }
        std::cout << "listen success" << std::endl;
    }

    void start()
    {
        struct sockaddr_in local;
        while (true)
        {
            memset(&local, 0, sizeof(local));
            socklen_t len = sizeof(local);
            int sock = accept(_listensock, (struct sockaddr *)&local, &len);
            std::string clientIp = inet_ntoa(local.sin_addr);
            uint16_t clientPort = ntohs(local.sin_port);
            if (sock < 0)
            {
                std::cout << "accept fail" << std::endl;
                exit(ACCEPT_ERR);
            }
            std::cout << clientIp << "-" << clientPort << "accept success" << std::endl;

            pid_t id = fork();
            if (id < 0)
            {
                std::cout << "fork occur fail " << std::endl;
                exit(FORK_ERR);
            }

            if (id == 0) // 子进程
            {
                close(_listensock);
                if (fork() > 0)
                    exit(0); // 退出子进程，保留孙子进程，此时孙子进程就变成了孤儿进程，由bash进行回收
                service(sock, clientIp, clientPort);
                exit(0);
            }
            close(sock); // 父进程关闭sock,socke给上面的孙子进程用就行了
        }
    }

    void service(int sock, std::string clientIp, uint16_t clientPort)
    {
        char buffer[1024];
        while (true)
        {
            int n = read(sock, buffer, sizeof(buffer) - 1);
            if (n == 0)
            {
                std::cout << clientIp << "-" << clientPort << " exit" << std::endl;
                exit(0);
            }
            else if (n < 0)
            {
                std::cout << "read occur fail" << std::endl;
                exit(READ_ERR);
            }
            else
            {
                buffer[n] = '\0';
                std::cout << clientIp << "-" << clientPort << " send message : " << buffer << " to me" << std::endl;
                std::string message = _func(buffer);
                int n = write(sock, message.c_str(), message.size());
                if (n < 0)
                {
                    std::cout << "write fail" << std::endl;
                    exit(WRITE_ERR);
                }
                std::cout << "I send message : " << message << " to " << clientIp << "-" << clientPort << std::endl;
            }
        }
    }

    ~ns_server()
    {
    }

private:
    int _listensock;
    uint16_t _port;
    func_t _func;
};
